package com.demo.sendmsg;

import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * @author admin
 */
@Slf4j
public class ReadFileSendMessage {
    static List<String> list_7d7e = new ArrayList<>();

    public static void main(String[] args) {
        File file = new File("/Users/jasper/packet/0319-0014/");
        File[] array = file.listFiles();
        ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(60));
        for (int i = 0; i < array.length; i++) {
            System.out.println(i);
            SendMsg sendMsg = new SendMsg(array, i);
            service.submit(sendMsg);
        }
        service.shutdown();
    }

    public static byte[] transfer2Bytes(String input) {
//        input = input.replaceAll("<=", "");
        String[] arrs = input.split(" ");
        byte[] bytes = new byte[arrs.length];
        for (int i = 0; i < arrs.length; i++) {
            bytes[i] = (byte) Integer.parseInt(arrs[i], 16);
        }
        return bytes;
    }

    private static void setNewFlag(byte[] bs) {
        byte[] da = new byte[bs.length - 15];
        //System.arraycopy(bs, 13, da, 0, da.length);
        //System.arraycopy(bs, 13, da, 0, da.length);0902 校验2次
        //ctbox校验位
//		bs[bs.length - 4] = setNewFlagSub(da);
        //然后gnns校验位
        int idx = bs.length - 2;
        bs[idx] = bs[1];
        for (int j = 2; j < idx; j++)
            bs[idx] ^= bs[j];
    }

    private static void ctboxewFlag(byte[] bs) {
        byte[] da = new byte[bs.length - 15];
        System.arraycopy(bs, 13, da, 0, da.length);
        //System.arraycopy(bs, 13, da, 0, da.length);0902 校验2次
        //ctbox校验位
        bs[bs.length - 4] = setNewFlagSub(da);
        //然后gnns校验位
        int idx = bs.length - 2;
        bs[idx] = bs[1];
        for (int j = 2; j < idx; j++)
            bs[idx] ^= bs[j];
    }

    private static byte setNewFlagSub(byte[] da) {
        byte flag = da[1];// 从数据头开始
        for (int i = 2; i < da.length - 2; i++) {
            flag ^= da[i];
        }
        // 校验码
        return flag;
    }

    public static byte[] edit7d7e(byte[] b) {
        b = subBytes(b, 1, b.length - 2);
        for (int i = 0; i < b.length; i++) {
            if ("125".equals(String.valueOf(b[i]))) {
                String str = String.valueOf(i) + "," + "7d";
                list_7d7e.add(str);
            }
            if ("126".equals(String.valueOf(b[i]))) {
                String str = String.valueOf(i) + "," + "7e";
                list_7d7e.add(str);
            }
        }
        for (int i = 0; i < list_7d7e.size(); i++) {
            String str[] = list_7d7e.get(i).split(",");
            if (str[1].equals("7d")) {
                byte head[] = cutOutByte(b, Integer.valueOf(str[0]));
                int left = (b.length - head.length);
                byte mid[] = {(byte) Integer.parseInt("7d", 16), (byte) Integer.parseInt("01", 16)};
                byte tail[] = subBytes(b, Integer.valueOf(str[0]) + 1, left - 1);
                b = getMergeBytes(head, mid);
                b = getMergeBytes(b, tail);
                if (i == list_7d7e.size() - 1)
                    break;
                for (int j = (i + 1); j < list_7d7e.size(); j++) {
                    String next_str[] = list_7d7e.get(j).split(",");
                    int new_index = Integer.valueOf(next_str[0]) + 1;
                    list_7d7e.set(j, new_index + "," + next_str[1]);
                }

            }
            if (str[1].equals("7e")) {
                byte head[] = cutOutByte(b, Integer.valueOf(str[0]));
                int left = (b.length - head.length);
                byte mid[] = {(byte) Integer.parseInt("7d", 16), (byte) Integer.parseInt("02", 16)};
                byte tail[] = subBytes(b, Integer.valueOf(str[0]) + 1, left - 1);
                b = getMergeBytes(head, mid);
                b = getMergeBytes(b, tail);
                if (i == list_7d7e.size() - 1)
                    break;
                for (int j = (i + 1); j < list_7d7e.size(); j++) {
                    String next_str[] = list_7d7e.get(j).split(",");
                    int new_index = Integer.valueOf(next_str[0]) + 1;
                    list_7d7e.set(j, new_index + "," + next_str[1]);
                }
            }
        }
        byte tmp[] = {(byte) Integer.parseInt("7e", 16)};
        b = getMergeBytes(tmp, b);
        b = getMergeBytes(b, tmp);
        list_7d7e.clear();
        return b;
    }

    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        for (int i = begin; i < begin + count; i++) bs[i - begin] = src[i];
        return bs;
    }

    public static byte[] cutOutByte(byte[] b, int j) {
        if (b.length == 0 || j == 0) {
            return null;
        }
        byte[] bjq = new byte[j];
        for (int i = 0; i < j; i++) {
            bjq[i] = b[i];
        }
        return bjq;
    }

    /**
     * 合并两个byte数组
     *
     * @param pByteA
     * @param pByteB
     * @return
     */
    public static byte[] getMergeBytes(byte[] pByteA, byte[] pByteB) {
        int aCount = pByteA.length;
        int bCount = pByteB.length;
        byte[] b = new byte[aCount + bCount];
        for (int i = 0; i < aCount; i++) {
            b[i] = pByteA[i];
        }
        for (int i = 0; i < bCount; i++) {
            b[aCount + i] = pByteB[i];
        }
        return b;
    }

    static class SendMsg implements Runnable {
        private File[] array;
        private int number;

        public SendMsg(File[] array, int number) {
            this.array = array;
            this.number = number;
        }

        @Override
        public void run() {
            try {
                sendMsg(number, array);
            } catch (IOException | InterruptedException e) {
                log.error("readLine error ", e);
            }
        }
    }

    public static void sendMsg(int number, File[] array) throws IOException, InterruptedException {

        NioSocketConnector connector = new NioSocketConnector();
        // 设置编码过滤器
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ByteArrayCodecFactory()));
        // 设置事件处理器10.3.30.128，172.16.1.13,172.16.1.45,172.16.1.44
        connector.setHandler(new SenderReceiveHandler());
        // 建立连接172.30.2.188，172.16.16.18/172.16.18.112
        ConnectFuture cf = connector.connect(new InetSocketAddress("172.22.34.237", 16531));
        // 等待连接创建完成
        cf.awaitUninterruptibly();

        File absoluteFile = array[number].getAbsoluteFile();
        FileReader reader = new FileReader(absoluteFile);
        BufferedReader br = new BufferedReader(reader);
        String str;
        while ((str = br.readLine()) != null) {
            byte[] message = transfer2Bytes(str);
            Thread.sleep(40);
            // 发送消息
            System.out.println("current thread is " + Thread.currentThread().getName());
            cf.getSession().write(message);
        }
        br.close();
        reader.close();
        connector.dispose();
    }
}

